package com.duan.service.impl;

import com.duan.config.RedisCache;
import com.duan.service.KaptchaService;

import com.google.code.kaptcha.Producer;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author db
 * @version 1.0
 * @description KaptchaServiceImpl
 * @since 2024/10/6
 */
@Service
public class KaptchaServiceImpl implements KaptchaService {

    @Value("${captcha.type}")
    private String captchaType;

    @Value("${captcha.captchaEnabled}")
    private boolean captchaEnabled;

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;



    @Override
    public Map getCode() {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("captchaEnabled",captchaEnabled);
        if(!captchaEnabled){
            return resultMap;
        }

        // 保存验证码信息
        String uuid = UUID.randomUUID().toString();
        //用于缓存的key
        String verifyKey = "captcha_codes:"+ uuid;

        String capStr = null, code = null;
        BufferedImage image = null;
        if ("math".equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if ("char".equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisCache.setCacheObject(verifyKey,code,60, TimeUnit.SECONDS);

        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            throw new RuntimeException("获取验证码报错：" + e.getMessage());
        }
        resultMap.put("code", code);
        resultMap.put("img", Base64.encode(os.toByteArray()));
        return resultMap;
    }
}
